﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
using System.Data;
using DataAccess;

namespace Controller
{
    public class GenerateEavTableEventController
    {
        public event GenerateEavTableEventHandler GenerateEavTableCompleted;

        public void OnGenerateEavTableCompleted(GenerateEavTableEventArgs e)
        {
            if (GenerateEavTableCompleted != null)
            {
                GenerateEavTableCompleted(e);
            }
        }

        public void GenerateEavTable(EAVTable eavTable,ConnectionInformation CI, TableInformation tableInformation, out List<Column> list)
        {
            DataTable relationalTable = tableInformation.DataTable.Copy();

            int NumberOfRows = relationalTable.Rows.Count;
            int i;
            Int64 j;
            string OldHeaderName = string.Empty;
            StringBuilder ExceptionMessage = new StringBuilder();
            list = new List<Column>();
            int columnCount = eavTable.ColumnList.Count;
            try
            {
                eavTable.PartitionKey = eavTable.PartitionKey.Trim();
                
                if (eavTable.StartIndex < 0 && eavTable.RowKeyType== RowKeyType.SequentialKey)
                {
                    ExceptionMessage.Append("Invalid StartNumber. It must be positive integer number.");
                    ExceptionMessage.Append(Environment.NewLine);
                }
                if (eavTable.Increment <= 0 && eavTable.RowKeyType == RowKeyType.SequentialKey)
                {
                    ExceptionMessage.Append("Invalid Increment number. It must be positive integer number greater then zero.");
                    ExceptionMessage.Append(Environment.NewLine);
                }
                if (ExceptionMessage.Length != 0)
                {
                    string ExceptionMessageString = ExceptionMessage.ToString();
                    ExceptionMessage.Remove(0, ExceptionMessage.Length);
                    throw new Exception(ExceptionMessageString);
                }

                for (i = 0; i < eavTable.ColumnList.Count; i++)
                    eavTable.ColumnList[i].Type1 = eavTable.ColumnList[i].Type1.Replace("System.Windows.Controls.ComboBoxItem: ", "");

                for (i = 0; i < columnCount; i++)
                    list.Add(Column.DeepCopy(eavTable.ColumnList[i]));

                for (i = 0; i < columnCount; i++)
                {
                    if (eavTable.ColumnList[i].Name.Equals(eavTable.HeaderName))
                        OldHeaderName = tableInformation.ColumnList[i].Name;     

                    if (eavTable.ColumnList[i].IsImported == false)
                    {
                        relationalTable.Columns.Remove(tableInformation.ColumnList[i].Name);
                    }
                }

                for (i = 0; i < columnCount; i++)
                {
                    if (list[i].IsImported == false)
                    {
                        list.RemoveAt(i);
                        i--; columnCount--;
                    }
                }

                columnCount = list.Count;
                for (i = 0; i < columnCount; i++)
                {
                    relationalTable.Columns[i].ColumnName = list[i].Name;
                }

                list.Insert(0, new Column() { Name = "RowKey", IsImported = true, Type1 = "String" });
                list.Insert(0, new Column() { Name = "PartitionKey", IsImported = true, Type1 = "String" });


                relationalTable.Columns.Add("PartitionKey", typeof(string));
                relationalTable.Columns.Add("RowKey", typeof(string));

                if (eavTable.RowKeyType == RowKeyType.Guid)
                {
                    string guid = String.Empty;

                    for (i = 0; i < NumberOfRows; i++)
                    {
                        guid = Guid.NewGuid().ToString();
                        relationalTable.Rows[i]["PartitionKey"] = eavTable.PartitionKey;
                        relationalTable.Rows[i]["RowKey"] = guid.ToString();
                    }
                }

                else if (eavTable.RowKeyType == RowKeyType.SequentialKey)
                {
                    for (i = 0, j = eavTable.StartIndex; i < NumberOfRows; i++, j += eavTable.Increment)
                    {
                        relationalTable.Rows[i]["PartitionKey"] = eavTable.PartitionKey;
                        relationalTable.Rows[i]["RowKey"] = j.ToString();
                    }
                }

                else if (eavTable.RowKeyType == RowKeyType.TableHeader)
                {
                    if (eavTable.HeaderName == String.Empty || eavTable.HeaderName == null)
                    {
                        throw new Exception("Header not selected for row key.");
                    }

                    for (i = 0; i < NumberOfRows; i++)
                    {
                        relationalTable.Rows[i]["PartitionKey"] = eavTable.PartitionKey;
                        relationalTable.Rows[i]["RowKey"] = relationalTable.Rows[i][eavTable.HeaderName];
                    }

                    if (eavTable.ImportAsRegularColumn == false)
                    {
                        relationalTable.Columns.Remove(eavTable.HeaderName);

                        for (i = 0; i < list.Count; i++)
                            if (list[i].Name == eavTable.HeaderName)
                            { list.RemoveAt(i); break; }
                    }
                }

                else if (eavTable.RowKeyType == RowKeyType.Ticks)
                {
                    for (i = 0, j = System.DateTime.Now.Ticks; i < NumberOfRows; i++, j++)
                    {
                        relationalTable.Rows[i]["PartitionKey"] = eavTable.PartitionKey;
                        relationalTable.Rows[i]["RowKey"] = j.ToString();
                    }
                }

                relationalTable.Columns["PartitionKey"].SetOrdinal(0);

                relationalTable.Columns["RowKey"].SetOrdinal(1);

                eavTable.EavTable = relationalTable;
                GenerateEavTableCompleted(new GenerateEavTableEventArgs(eavTable));

            }
            catch (Exception ex)
            {
                GenerateEavTableCompleted(new GenerateEavTableEventArgs(ex));
            }

        }
    }
}
